package com.qianli.cashmama.trade.aop;

import com.alibaba.dubbo.rpc.*;
import com.alibaba.fastjson.JSON;
import com.fqgj.log.util.Constants;
import com.robert.vesta.util.IdUtils;
import org.apache.logging.log4j.ThreadContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
 * Created with IntelliJ IDEA.
 * User: pavan
 * Date: 2019/12/20
 * Time: 下午5:45
 */
public class DubboTraceServiceFilter implements Filter {

    private static final Logger LOGGER = LoggerFactory.getLogger(DubboTraceServiceFilter.class);

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        String traceId = RpcContext.getContext().getAttachment(Constants.TRACE_ID);
        if (traceId != null) {
            ThreadContext.put(Constants.TRACE_ID, traceId);
        } else {
            ThreadContext.put(Constants.TRACE_ID, IdUtils.genId() + "");
        }
        String ip = RpcContext.getContext().getRemoteHost();
        long time = System.currentTimeMillis();
        Result result = invoker.invoke(invocation);
        long timediff = System.currentTimeMillis() - time;
        if (timediff >= 200) {
            LOGGER.warn("DubboTraceServiceFilter,take a long time:{},ip:{},methodName:{},request:{}", timediff, ip, invocation.getMethodName(), JSON.toJSONString(invocation.getArguments()));
        }
        return result;
    }
}
